package controller;

import pojo.Goods;
import pojo.OrderDetail;
import pojo.OrderGoodsInfo;
import service.IGoodsService;
import service.IOrderService;
import service.impl.GoodsServiceImpl;
import service.impl.OrderServiceImpl;
import utils.NoLoginUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "OrderDetailServlet", value = "/order-detail")
public class OrderDetailServlet extends HttpServlet {
    private IOrderService orderService;
    private IGoodsService goodsService;

    @Override
    public void init() throws ServletException {
        orderService = new OrderServiceImpl();
        goodsService = new GoodsServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null) {
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            return;
        }
        String id = request.getParameter("id");
        if (id == null || "".equals(id)) {
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
            return;
        }
        OrderDetail orderDetail = null;
        List<OrderGoodsInfo> orderGoodsInfos = null;
        List<Goods> goodsList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();
        BigDecimal sum = new BigDecimal("0");
        try {
            orderDetail = orderService.queryOrderDetailById(id);
            orderGoodsInfos = orderService.queryOrderGoodsInfosById(id);
            for (OrderGoodsInfo info : orderGoodsInfos) {
                int gid = info.getGid();
                Goods goods = goodsService.queryGoodsById(gid);
                goodsList.add(goods);
                int count = info.getCount();
                countList.add(count);
            }
            for (int i = 0; i < goodsList.size(); i++) {
                BigDecimal price = goodsList.get(i).getPrice();
                BigDecimal num = new BigDecimal(countList.get(i));
                sum = sum.add(price.multiply(num));
            }
            request.setAttribute("sum", sum);
            request.setAttribute("countList", countList);
            request.setAttribute("goodsList", goodsList);
            request.setAttribute("orderDetail", orderDetail);
            request.setAttribute("orderGoodsInfos", orderGoodsInfos);
        } catch (Exception e) {
            request.getRequestDispatcher("/WEB-INF/error.jsp").forward(request, response);
        }
        request.getRequestDispatcher("/WEB-INF/order_detail.jsp").forward(request, response);
    }
}
